package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.MdmOrgAddDto;
import com.kaili.basic.pojo.dto.MdmOrgQueryByPageDto;
import com.kaili.basic.pojo.dto.MdmOrgQueryDto;
import com.kaili.basic.pojo.dto.MdmOrgUpdateDto;
import com.kaili.basic.pojo.entity.MdmOrgEntity;
import com.kaili.basic.pojo.vo.MdmOrgQueryAllVo;
import com.kaili.basic.service.IMdmOrgService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.exception.RestException;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.ExcelUtil;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Desc: 组织机构的管理
 * @author: TBS
 * @Time: 2019/8/1 18:57
 * @Copyright: © 2018 杭州凯立通信有限公司 版权所有
 * @Warning: 本内容仅限于公司内部传阅,禁止外泄或用于其它商业目的
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "组织机构管理",description = "组织机构相关API")
@RestController
public class MdmOrgController {
    public volatile String orgCode;

    private static Logger log = LoggerFactory.getLogger(MdmOrgController.class);
    @Autowired
    private IMdmOrgService mdmOrgService;

    /**
    * @Desc:  新增组织机构
    * @author: TBS
    * @Time: 2019/8/9 11:23
    * @param mdmOrgAddDto
    * @return com.kaili.common.response.RestStatus
    */
    @ApiOperation(value = "新增组织机构")
    @PostMapping("org/add")
    public RestStatus addOrg(@Validated @RequestBody MdmOrgAddDto mdmOrgAddDto){
        MdmOrgEntity mdmOrgEntity1 = new MdmOrgEntity();
        mdmOrgEntity1.setOrgCode(mdmOrgAddDto.getOrgCode());
        mdmOrgEntity1.setOrgName(mdmOrgAddDto.getOrgName());
        Integer count = mdmOrgService.queryDprvOrg(mdmOrgEntity1);
        if(count>0){
            return CommonStatus.RENT_REPETITION;
        }
        mdmOrgAddDto.setCreateBy(LoginDetailUtils.getCurrent().getId());
        mdmOrgAddDto.setCreateTime(new Date());
        MdmOrgEntity mdmOrgEntity = ObjectUtils.toObject(mdmOrgAddDto, MdmOrgEntity.class);

        mdmOrgService.add(mdmOrgEntity);
        return CommonStatus.ADD_OK;
    }
    /**
    * @Desc:  删除组织机构
    * @author: TBS
    * @Time: 2019/8/9 11:23
    * @param id
    * @return com.kaili.common.response.RestStatus
    */
    @ApiOperation(value = "删除组织机构")
    @DeleteMapping("org/{id}")
    public RestStatus deleteOrg(@PathVariable("id") int id){
        mdmOrgService.delete(id);
        return CommonStatus.DELETE_OK;
    }

    /**
    * @Desc:  修改组织机构
    * @author: TBS
    * @Time: 2019/8/9 11:24
    * @param mdmOrgUpdateDto
    * @return com.kaili.common.response.RestStatus
    */
    @ApiOperation(value = "修改组织机构")
    @PutMapping("org")
    public RestStatus updateOrg( @RequestBody MdmOrgUpdateDto mdmOrgUpdateDto){
        mdmOrgUpdateDto.setModifyBy(LoginDetailUtils.getCurrent().getId());
        mdmOrgUpdateDto.setModifyTime(new Date());
        MdmOrgEntity mdmOrgEntity = ObjectUtils.toObject(mdmOrgUpdateDto, MdmOrgEntity.class);
        mdmOrgService.update(mdmOrgEntity);
        return CommonStatus.UPDATE_OK;
    }

    /**
    * @Desc:  分页查询组织机构
    * @author: TBS
    * @Time: 2019/8/9 11:24
    * @param mdmOrgQueryByPageDto
    * @return com.baomidou.mybatisplus.plugins.Page<com.kaili.basic.pojo.vo.MdmOrgQueryAllVo>
    */
    @ApiOperation(value = "分页查询组织机构")
    @GetMapping("org")
    public Page<MdmOrgQueryAllVo> queryPageList(MdmOrgQueryByPageDto mdmOrgQueryByPageDto){
        return mdmOrgService.queryPageList(new Page<>(mdmOrgQueryByPageDto.getPage(),mdmOrgQueryByPageDto.getPageSize()),mdmOrgQueryByPageDto);
    }
    @ApiOperation(value = "通过ID精确查询组织机构")
    @GetMapping("org/byId/{id}")
    public MdmOrgEntity queryOrgById(@PathVariable("id") int id){
        return mdmOrgService.queryOrgById(id);
    }

    /**
    * @Desc:  机构导出
    * @author: TBS
    * @Time: 2019/8/9 11:24
    * @param response
    * @param mdmOrgQueryByPageDto
    * @return void
    */
    @GetMapping("org/export")
    @ApiOperation(value = "机构导出")
    public void export(HttpServletResponse response, @ModelAttribute MdmOrgQueryByPageDto mdmOrgQueryByPageDto) throws RestException {
        List<MdmOrgQueryAllVo> list = mdmOrgService.queryOrgExport(mdmOrgQueryByPageDto);
        ExcelUtil.exportExcel(list,"机构信息","sheet1", MdmOrgQueryAllVo.class, UUID.randomUUID().toString()+".xls",response);
    }

    /**
    * @Desc:  机构导入
    * @author: TBS
    * @Time: 2019/8/9 11:24
    * @param file
    * @return void
    */
    @PostMapping("org/import")
    @ApiOperation(value = "机构导入")
    public void export(MultipartFile file) throws RestException {
        List<MdmOrgQueryAllVo> list = ExcelUtil.importExcel(file,1,1, MdmOrgQueryAllVo.class);
        MdmOrgEntity mdmOrgEntity;
        for (MdmOrgQueryAllVo mdmOrgQueryAllVo : list) {
            mdmOrgQueryAllVo.setCreateBy(LoginDetailUtils.getCurrent().getId());
            mdmOrgQueryAllVo.setCreateTime(new Date());
            mdmOrgEntity = ObjectUtils.toObject(mdmOrgQueryAllVo, MdmOrgEntity.class);
            mdmOrgService.add(mdmOrgEntity);
        }
    }

    /**
    * @Desc:  条件查询mdm消息
    * @author: TBS
    * @Time: 2019/8/9 11:24
    * @param mdmOrgQueryDto
    * @return java.util.List<com.kaili.basic.pojo.entity.MdmOrgEntity>
    */
    @ResponseBody
    @GetMapping(value = "org/searchRanges")
    @ApiOperation(value = "条件查询mdm消息",notes = "条件查询mdm消息,条件都是不必填")
    public List<MdmOrgEntity> queryMdmMessages(@ModelAttribute MdmOrgQueryDto mdmOrgQueryDto) {
        return mdmOrgService.queryOrgRanges(mdmOrgQueryDto);
    }

    /**
    * @Desc:  查询Org表中的code和name
    * @author: TBS
    * @Time: 2019/8/9 19:08
    *
    * @return com.kaili.basic.pojo.entity.MdmOrgEntity
    */
    @ApiOperation(value = "查询Org表中的code和name")
    @GetMapping(value = "/org/getCodeName")
    public List<MdmOrgEntity> getCodeName(){
        return mdmOrgService.getCodeName();
    }


    /**
    * @Desc:  新增机构时获取机构编码
    * @author: TBS
    * @Time: 2019/8/9 11:24
    *
    * @return java.lang.String
    */
    @ApiOperation(value = "新增机构时获取机构编码")
    @GetMapping("org/code")
    public String getOrgCode(){
        if(orgCode==null||"".equals(orgCode)) {
            String oldCode = mdmOrgService.getCode();
            orgCode = addValue(oldCode);
        }else{
            orgCode = addValue(orgCode);
        }
        return orgCode;
    }

    /**
    * @Desc:  新增分组时获取分组编号 调用addValue方法
    * @author: TBS
    * @Time: 2019/8/9 11:24
    * @param str
    * @return java.lang.String
    */
    public static String addValue(String str){
        Integer str1 = Integer.parseInt(str);
        String str2 = str1.toString();
        int index = str.length()-str2.length()-1;

        int temp =0;

        //以0开头的
        if (str.startsWith("0")&&index!=-1){
            temp=index+1;
        }
        Integer integer = null;
        try {
            integer = Integer.valueOf(str);
        } catch (NumberFormatException e) {
            log.info("输入的字符串不是纯数字字符串...");
        }
        integer++;
        String newNum = integer.toString();

        if (newNum.length()>str.length()-temp){
            temp--;
        }
        StringBuffer sb = new StringBuffer();
        if (temp!=0){
            for (int i =0 ;i<temp ;i++){
                sb.append("0");
            }
        }
        sb.append(newNum);
        return sb.toString();
    }
}